package pers.duorhs.csr.socket;

import com.alibaba.fastjson.JSON;
import io.socket.client.IO;
import io.socket.client.Socket;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.duorhs.common.config.SocketProperties;
import pers.duorhs.common.socket.SocketClientHandler;
import pers.duorhs.common.socket.SocketConstance;
import pers.duorhs.common.socket.SocketData;

/**
 * 模拟前端的Socket实现
 *
 * @author Duorhs
 * @date 2022/5/9 9:38
 */
@Component
@Slf4j
public class CsrSocketClientHandler implements SocketClientHandler {
    private final SocketProperties properties;

    @Autowired
    public CsrSocketClientHandler(SocketProperties properties) {
        this.properties = properties;
    }

    @SneakyThrows
    @Override
    public void login(String name, String room) {
        String url = "http://" + properties.getHost() + ":" + properties.getPort();
        IO.Options options = new IO.Options();
        options.transports = new String[]{"websocket"};
        options.reconnectionAttempts = 2;
        options.reconnectionDelay = 1000;
        options.timeout = 5000;
        options.query = "user=" + name + "@" + room;
        Socket socket = IO.socket(url, options);
        //注册事件
        socket.on(Socket.EVENT_CONNECT, args -> System.out.println(name + " 客户端连接成功~"));
        socket.on(Socket.EVENT_DISCONNECT, args -> {
            if (name.equals(args[0])) {
                socket.disconnect();
                log.info("{} 客户端断开连接", name);
            }
        });
        //socket.on("msg", args -> System.out.println("Server -> " + name + ": " + Arrays.toString(args)));
        socket.on(SocketConstance.EVENT, args -> {
            SocketData socketData = JSON.parseObject(args[0].toString(), SocketData.class);
            Object customer = socketData.getHead().get("customer");
            Object employee = socketData.getHead().get("employee");
            if (employee.equals(name)) {
                System.out.println("这是客户 " + customer + " 给坐席 " + employee + "发送的消息: " + socketData.getBody());
            }

        });

        socket.connect();
    }

}
